package com.secsbrain.cmdb.biz.impl;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import com.secsbrain.cmdb.biz.IIpService;
import com.secsbrain.cmdb.web.dto.IpTest;
import com.secsbrain.sso.core.SsoHelper;
import com.secsbrain.sso.model.dto.system.UserDetailDTO;
import com.secsbrain.cmdb.dal.mapper.IpMapper;
import com.secsbrain.cmdb.dal.model.Ip;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import com.baomidou.framework.service.impl.SuperServiceImpl;
import com.baomidou.mybatisplus.plugins.Page;

/**
 *
 * Ip 表数据服务层接口实现类
 *
 */
@Service
public class IpServiceImpl extends SuperServiceImpl<IpMapper, Ip> implements IIpService {

	/* (non-Javadoc)
	 * @see IIpService#updateIp(java.util.List)
	 */
	@Override
	public void updateIp(List<IpTest> ipTestList) {
		UserDetailDTO userDetailDTO= SsoHelper.currentUser();
		
		for(IpTest ipTest:ipTestList){
			Ip ipParam=new Ip();
			ipParam.setIp(ipTest.getIp());
			int count=this.selectCount(ipParam);
			if(count>0){
				Ip ipUp=new Ip();
				ipUp.setIstatus(ipTest.isConnect()?0:1);
				ipUp.setUpdateTime(new Date());
				if(userDetailDTO!=null){
					ipUp.setUpdatorId(userDetailDTO.getId());
					ipUp.setUpdatorName(userDetailDTO.getNickname());
				}else{
					ipUp.setUpdatorName("定时任务");
				}
				
				Ip ipWhere=new Ip();
				ipWhere.setIp(ipTest.getIp());
				this.updateSelective(ipUp, ipWhere);
			}else{
				Ip ipInsert=new Ip();
				ipInsert.setIstatus(ipTest.isConnect()?0:1);
				ipInsert.setUpdateTime(new Date());
				ipInsert.setIp(ipTest.getIp());
				if(userDetailDTO!=null){
					ipInsert.setUpdatorId(userDetailDTO.getId());
					ipInsert.setUpdatorName(userDetailDTO.getNickname());
				}else{
					ipInsert.setUpdatorName("定时任务");
				}
				this.insertSelective(ipInsert);
			}
		}
	}

	/* (non-Javadoc)
	 * @see IIpService#queryIpPageList(com.baomidou.mybatisplus.plugins.Page, Ip)
	 */
	@Override
	public Page<Ip> queryIpPageList(Page<Ip> page, Ip entity) {
		if(StringUtils.isNotEmpty(entity.getIpSegment())){
	        String ipSegment=entity.getIpSegment().substring(0, entity.getIpSegment().lastIndexOf(".")+1);
	        List<String> ipList=new ArrayList<String>();
	        for(int i=0;i<254;i++){
	        	ipList.add(ipSegment+i);
	        }
	        String[] ipArray=ipList.toArray(new String[ipList.size()]);
			entity.setIpArray(ipArray);
		}
		page.setRecords(this.baseMapper.queryIpPageList(page, entity));
		return page;
	}

}